package com.softeem.gulimail.product.exception;

import com.softeem.common.exception.BizCodeEnum;
import com.softeem.common.utils.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.softeem.gulimail.product.controller")
public class ProductExcetionHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validHandlerException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题-{}，异常类型：{}",e.getMessage(),e.getClass());
        Map<String,String> exceptionMap = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach((item)->
                        exceptionMap.put(item.getField(),item.getDefaultMessage())
                );
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",exceptionMap);
    }
    @ExceptionHandler(value = Throwable.class)
    public R otherHandlerException(Exception e){
        log.error("错误",e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
